/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.aaron.platform.service;

import com.aaron.platform.dao.IDomainDao;
import com.aaron.platform.entity.ItscDomainInfo;
import com.aaron.platform.exceptions.DomainNotExistException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author mac
 */
public class DomainServiceImp implements IDomainService {

    private IDomainDao domainDao;

    public void setDomainDao(IDomainDao domainDao) {
        this.domainDao = domainDao;
    }

    public ItscDomainInfo findById(Integer orgId) throws DomainNotExistException {
        ItscDomainInfo itscOrgInfo = domainDao.findById(orgId);
        if (itscOrgInfo == null) {
            throw new DomainNotExistException();
        }
        return itscOrgInfo;
    }

    public ItscDomainInfo findByName(String orgName) throws DomainNotExistException {
        ItscDomainInfo itscOrgInfo = domainDao.findByName(orgName);
        if (itscOrgInfo == null) {
            throw new DomainNotExistException();
        }
        return itscOrgInfo;
    }

    public ItscDomainInfo findTopDomain() {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ItscDomainInfo.class);
        detachedCriteria.add(Restrictions.isNull(ItscDomainInfo.PROPERTY_PARENT_ORG));
        List<ItscDomainInfo> itscOrgInfos = domainDao.findByCriteria(detachedCriteria);
        return itscOrgInfos.get(0);
    }

    public List<ItscDomainInfo> findAllDomains() {
        return domainDao.FindAll();
    }

    /**
     * 找到所有二级域名，只支持二级
     * @param orgId
     * @return 
     */
    public List<ItscDomainInfo> findSubDomains(Integer orgId) {
        List<ItscDomainInfo> domainInfos = new ArrayList<ItscDomainInfo>();
        ItscDomainInfo topDomain;
        try {
            topDomain = findById(orgId);
        } catch (DomainNotExistException ex) {
            return null;
        }
        for (ItscDomainInfo domainInfo : topDomain.getChildDomains()) {
            domainInfos.add(domainInfo);
        }
        return  domainInfos;
    }
}
